package com.lagou.thread;

import com.lagou.model.Request;
import com.lagou.model.RequestBuilder;
import com.lagou.model.Response;
import com.lagou.v4.coyote.CoyoteAdaptor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author Kirito
 * @description:
 * @date 2020/04/25
 */
public class RequestProcessor extends Thread {

    private Socket socket;

    private CoyoteAdaptor adaptor;

    public RequestProcessor(Socket socket, CoyoteAdaptor adaptor) {
        this.socket = socket;
        this.adaptor = adaptor;
    }

    @Override
    public void run() {
        try {
            // 获取输入/输出流信息
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            // 根据请求信息获取request/response对象
            Request request = new RequestBuilder().buildRequest(inputStream);
            Response response = new Response(outputStream);

            // 获取连接器适配器，将request/response转换成ServletRequest/ServletResponse
            adaptor.service(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭Socket连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
